import 'dart:async';

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

typedef TimeListenerCallback = void Function(FpgaTimeNotifier notifier);

class FpgaTimeNotifier extends ChangeNotifier {
  final List<TimeListenerCallback> _timeListener = [];
  late DateTime _now;

  FpgaTimeNotifier(){
    super.addListener(_timeListenerCallback);
  }

  DateTime get now => _now;

  String format([String format = "HH:mm:ss"]) {
    DateFormat dateFormat = DateFormat(format);
    return dateFormat.format(_now);
  }

  void init(String fpgaTime) {
    List<String> list = fpgaTime.split(":");
    _now = DateTime.now().copyWith(hour: int.parse(list[0]), minute: int.parse(list[1]), second: int.parse(list[2]));
    Timer.periodic(const Duration(seconds: 1), (timer) {
      _now = _now.add(const Duration(seconds: 1));
      notifyListeners();
    });
  }

  void addTimeListener(TimeListenerCallback listener) {
    if (!_timeListener.contains(listener)) _timeListener.add(listener);
  }

  void removeTimeListener(TimeListenerCallback listener) {
    if (_timeListener.contains(listener)) _timeListener.remove(listener);
  }

  void _timeListenerCallback() {
    for (TimeListenerCallback callback in _timeListener) {
      callback(this);
    }
  }
}
